package com.coldchain.resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UploadController {
    private  static final Logger log= LoggerFactory.getLogger(UploadController.class);
    @Value("${update.http}")
    private  String updateHttp ;
    @Value("${update.dir}")
    private String updateDir;




    @PostMapping("/upload/{dirName}/{fileType}")
    public Object singleFileUpload(@PathVariable(value = "dirName",required = true) String dirName,
                                   @PathVariable(value = "fileType",required = true) String fileTypeName,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {
        List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("file");
        Map<String,Object> dataMap=new HashMap<>();

        try {
            dataMap.put("status",200);
            if(files.isEmpty()) {
                response.setStatus(500);
                try {
                    response.getWriter().write("请选择需要上传的文件");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            List<String> filePaths=new ArrayList<>();
            files.forEach((v->{
                filePaths.add(copyFile(dirName,fileTypeName,v));
            }));
            dataMap.put("data",filePaths);
        }catch (Exception e){
            log.error("update error:{}",e.getMessage());
            dataMap.put("status",500);
            dataMap.put("message","上传失败");
        }


        return dataMap;
    }

    /**
     * 复制文件到本地并返回下载地址
     * @param dirName
     * @param fileType
     * @param file
     * @return
     */
    private String copyFile(String dirName,String fileType,MultipartFile file){
        String filePath="";
        try {
            String f= MD5Utils.getMD5Str(file.getOriginalFilename()).concat(".").concat(getFileSuffix(file.getOriginalFilename()));
            byte[] bytes = file.getBytes();
            File dirFile=new File(updateDir.concat(File.separator).concat(dirName).concat(File.separator).concat(fileType));
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }
            File fp=new File(dirFile.getPath().concat(File.separator).concat(f));
            if(!fp.isFile()){
                Path path = Paths.get(fp.getPath());
                Files.write(path, bytes);

            }
            filePath=getFileDwoPath(dirName,fileType,f);
        } catch (Exception e) {
            log.error("upload error:{}",e.getMessage());

        }finally {
            return filePath;
        }

    }

    private String getFileDwoPath(String dirPath,String fileType,String fileName){
        return updateHttp.concat("/dowload?f=").concat(fileName).concat("&d=").concat(dirPath).concat("&t=").concat(fileType);

    }
    private String getFileSuffix(String fileName){
        return  fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}
